import React, { useMemo } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line, PieChart, Pie, Cell } from 'recharts';
import { useDiaryStore } from '../../store/diaryStore';
import { TrendingUp, TrendingDown, Minus, Calendar, Target, Award, Clock } from 'lucide-react';

interface ComparativeAnalyticsProps {
  className?: string;
}

interface ComparisonData {
  metric: string;
  current: number;
  previous: number;
  change: number;
  changePercent: number;
  trend: 'up' | 'down' | 'stable';
  icon: React.ReactNode;
  unit?: string;
}

interface MonthlyComparison {
  month: string;
  entries: number;
  avgMood: number;
  uniqueTags: number;
  longestStreak: number;
}

const ComparativeAnalytics: React.FC<ComparativeAnalyticsProps> = ({ className = '' }) => {
  const entries = useDiaryStore((state) => state.entries);
  const getStats = useDiaryStore((state) => state.getStats);
  
  const analytics = useMemo(() => {
    const now = new Date();
    const currentMonth = now.getMonth();
    const currentYear = now.getFullYear();
    
    // Get current month data
    const currentMonthStart = new Date(currentYear, currentMonth, 1);
    const currentMonthEnd = new Date(currentYear, currentMonth + 1, 0);
    
    // Get previous month data
    const prevMonth = currentMonth === 0 ? 11 : currentMonth - 1;
    const prevYear = currentMonth === 0 ? currentYear - 1 : currentYear;
    const prevMonthStart = new Date(prevYear, prevMonth, 1);
    const prevMonthEnd = new Date(prevYear, prevMonth + 1, 0);
    
    // Filter entries for current and previous month
    const currentMonthEntries = entries.filter(entry => {
      const entryDate = new Date(entry.createdAt);
      return entryDate >= currentMonthStart && entryDate <= currentMonthEnd;
    });
    
    const prevMonthEntries = entries.filter(entry => {
      const entryDate = new Date(entry.createdAt);
      return entryDate >= prevMonthStart && entryDate <= prevMonthEnd;
    });
    
    // Calculate metrics for both months
    const calculateMetrics = (monthEntries: typeof entries) => {
      const totalEntries = monthEntries.length;
      
      // Calculate average mood (assuming mood is stored as a number or can be converted)
      const moodValues = monthEntries
        .map(entry => {
          // Convert mood to numeric value for calculation
          const moodMap: Record<string, number> = {
            'very-happy': 5, 'happy': 4, 'neutral': 3, 'sad': 2, 'very-sad': 1,
            'excited': 5, 'content': 4, 'calm': 3, 'anxious': 2, 'depressed': 1
          };
          return moodMap[entry.mood] || 3;
        })
        .filter(Boolean);
      
      const avgMood = moodValues.length > 0 
        ? moodValues.reduce((sum, mood) => sum + mood, 0) / moodValues.length 
        : 0;
      
      // Calculate unique tags
      const allTags = monthEntries.flatMap(entry => entry.tags || []);
      const uniqueTags = new Set(allTags).size;
      
      // Calculate writing streak for the month
      const sortedDates = monthEntries
        .map(entry => new Date(entry.createdAt).toDateString())
        .filter((date, index, arr) => arr.indexOf(date) === index)
        .sort();
      
      let longestStreak = 0;
      let currentStreak = 0;
      
      for (let i = 0; i < sortedDates.length; i++) {
        if (i === 0) {
          currentStreak = 1;
        } else {
          const prevDate = new Date(sortedDates[i - 1]);
          const currDate = new Date(sortedDates[i]);
          const dayDiff = (currDate.getTime() - prevDate.getTime()) / (1000 * 60 * 60 * 24);
          
          if (dayDiff === 1) {
            currentStreak++;
          } else {
            longestStreak = Math.max(longestStreak, currentStreak);
            currentStreak = 1;
          }
        }
      }
      longestStreak = Math.max(longestStreak, currentStreak);
      
      // Calculate average words per entry
      const totalWords = monthEntries.reduce((sum, entry) => {
        const wordCount = entry.content.replace(/<[^>]*>/g, ' ').split(/\s+/).filter(word => word.length > 0).length;
        return sum + wordCount;
      }, 0);
      const avgWordsPerEntry = totalEntries > 0 ? totalWords / totalEntries : 0;
      
      return {
        totalEntries,
        avgMood,
        uniqueTags,
        longestStreak,
        avgWordsPerEntry,
        totalWords
      };
    };
    
    const currentMetrics = calculateMetrics(currentMonthEntries);
    const prevMetrics = calculateMetrics(prevMonthEntries);
    
    // Create comparison data
    const createComparison = (
      metric: string,
      current: number,
      previous: number,
      icon: React.ReactNode,
      unit = ''
    ): ComparisonData => {
      const change = current - previous;
      const changePercent = previous > 0 ? (change / previous) * 100 : 0;
      const trend = change > 0.1 ? 'up' : change < -0.1 ? 'down' : 'stable';
      
      return {
        metric,
        current,
        previous,
        change,
        changePercent,
        trend,
        icon,
        unit
      };
    };
    
    const comparisons: ComparisonData[] = [
      createComparison(
        'Total Entries',
        currentMetrics.totalEntries,
        prevMetrics.totalEntries,
        <Calendar className="w-5 h-5" />
      ),
      createComparison(
        'Average Mood',
        currentMetrics.avgMood,
        prevMetrics.avgMood,
        <Target className="w-5 h-5" />,
        '/5'
      ),
      createComparison(
        'Unique Tags',
        currentMetrics.uniqueTags,
        prevMetrics.uniqueTags,
        <Award className="w-5 h-5" />
      ),
      createComparison(
        'Longest Streak',
        currentMetrics.longestStreak,
        prevMetrics.longestStreak,
        <Clock className="w-5 h-5" />,
        ' days'
      ),
      createComparison(
        'Avg Words/Entry',
        Math.round(currentMetrics.avgWordsPerEntry),
        Math.round(prevMetrics.avgWordsPerEntry),
        <TrendingUp className="w-5 h-5" />,
        ' words'
      )
    ];
    
    // Monthly trend data for the last 6 months
    const monthlyTrends: MonthlyComparison[] = [];
    for (let i = 5; i >= 0; i--) {
      const date = new Date(currentYear, currentMonth - i, 1);
      const monthStart = new Date(date.getFullYear(), date.getMonth(), 1);
      const monthEnd = new Date(date.getFullYear(), date.getMonth() + 1, 0);
      
      const monthEntries = entries.filter(entry => {
        const entryDate = new Date(entry.createdAt);
        return entryDate >= monthStart && entryDate <= monthEnd;
      });
      
      const metrics = calculateMetrics(monthEntries);
      
      monthlyTrends.push({
        month: date.toLocaleDateString('en-US', { month: 'short', year: '2-digit' }),
        entries: metrics.totalEntries,
        avgMood: Number(metrics.avgMood.toFixed(1)),
        uniqueTags: metrics.uniqueTags,
        longestStreak: metrics.longestStreak
      });
    }
    
    return {
      comparisons,
      monthlyTrends,
      currentMonth: currentMonthStart.toLocaleDateString('en-US', { month: 'long', year: 'numeric' }),
      previousMonth: prevMonthStart.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })
    };
  }, [entries]);
  
  const getTrendIcon = (trend: 'up' | 'down' | 'stable') => {
    switch (trend) {
      case 'up':
        return <TrendingUp className="w-4 h-4 text-green-600" />;
      case 'down':
        return <TrendingDown className="w-4 h-4 text-red-600" />;
      default:
        return <Minus className="w-4 h-4 text-gray-600" />;
    }
  };
  
  const getTrendColor = (trend: 'up' | 'down' | 'stable') => {
    switch (trend) {
      case 'up':
        return 'text-green-600 bg-green-50';
      case 'down':
        return 'text-red-600 bg-red-50';
      default:
        return 'text-gray-600 bg-gray-50';
    }
  };

  return (
    <div className={`space-y-6 ${className}`}>
      {/* Header */}
      <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
        <h2 className="text-xl font-semibold text-warm-gray-800 mb-2">
          Comparative Analytics
        </h2>
        <p className="text-sm text-warm-gray-600">
          Comparing {analytics.currentMonth} with {analytics.previousMonth}
        </p>
      </div>

      {/* Key Metrics Comparison */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
        {analytics.comparisons.map((comparison, index) => (
          <div key={index} className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="text-warm-gray-600">
                {comparison.icon}
              </div>
              <div className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${
                getTrendColor(comparison.trend)
              }`}>
                {getTrendIcon(comparison.trend)}
                {Math.abs(comparison.changePercent).toFixed(1)}%
              </div>
            </div>
            
            <div className="space-y-1">
              <h3 className="text-sm font-medium text-warm-gray-700">
                {comparison.metric}
              </h3>
              <div className="text-2xl font-bold text-warm-gray-900">
                {comparison.current.toFixed(comparison.unit === '/5' ? 1 : 0)}{comparison.unit}
              </div>
              <div className="text-xs text-warm-gray-500">
                Previous: {comparison.previous.toFixed(comparison.unit === '/5' ? 1 : 0)}{comparison.unit}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Monthly Trends Chart */}
      <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
        <h3 className="text-lg font-semibold text-warm-gray-800 mb-4">
          6-Month Trend Analysis
        </h3>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Entries Trend */}
          <div>
            <h4 className="text-sm font-medium text-warm-gray-700 mb-3">Monthly Entries</h4>
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={analytics.monthlyTrends}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f3f4f6" />
                <XAxis dataKey="month" stroke="#6b7280" fontSize={12} />
                <YAxis stroke="#6b7280" fontSize={12} />
                <Tooltip 
                  contentStyle={{
                    backgroundColor: '#ffffff',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px'
                  }}
                />
                <Bar dataKey="entries" fill="#3b82f6" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
          
          {/* Mood Trend */}
          <div>
            <h4 className="text-sm font-medium text-warm-gray-700 mb-3">Average Mood Trend</h4>
            <ResponsiveContainer width="100%" height={200}>
              <LineChart data={analytics.monthlyTrends}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f3f4f6" />
                <XAxis dataKey="month" stroke="#6b7280" fontSize={12} />
                <YAxis domain={[1, 5]} stroke="#6b7280" fontSize={12} />
                <Tooltip 
                  contentStyle={{
                    backgroundColor: '#ffffff',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px'
                  }}
                />
                <Line 
                  type="monotone" 
                  dataKey="avgMood" 
                  stroke="#10b981" 
                  strokeWidth={3}
                  dot={{ fill: '#10b981', strokeWidth: 2, r: 4 }}
                />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Performance Insights */}
      <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
        <h3 className="text-lg font-semibold text-warm-gray-800 mb-4">
          Performance Insights
        </h3>
        
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {/* Writing Consistency */}
          <div className="p-4 bg-blue-50 rounded-lg">
            <h4 className="font-medium text-blue-800 mb-2">📝 Writing Consistency</h4>
            <p className="text-sm text-blue-700">
              {analytics.comparisons[0].trend === 'up' 
                ? 'Great job! You\'re writing more consistently this month.' 
                : analytics.comparisons[0].trend === 'down'
                ? 'Try to maintain a regular writing schedule.'
                : 'You\'re maintaining steady writing habits.'}
            </p>
          </div>
          
          {/* Mood Tracking */}
          <div className="p-4 bg-green-50 rounded-lg">
            <h4 className="font-medium text-green-800 mb-2">😊 Mood Progress</h4>
            <p className="text-sm text-green-700">
              {analytics.comparisons[1].trend === 'up' 
                ? 'Your mood has been improving! Keep it up.' 
                : analytics.comparisons[1].trend === 'down'
                ? 'Consider what might be affecting your mood.'
                : 'Your mood has been stable this month.'}
            </p>
          </div>
          
          {/* Engagement Level */}
          <div className="p-4 bg-purple-50 rounded-lg">
            <h4 className="font-medium text-purple-800 mb-2">🎯 Engagement</h4>
            <p className="text-sm text-purple-700">
              {analytics.comparisons[2].trend === 'up' 
                ? 'You\'re exploring more topics and themes!' 
                : analytics.comparisons[2].trend === 'down'
                ? 'Try writing about different aspects of your life.'
                : 'You\'re maintaining good topic diversity.'}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ComparativeAnalytics;